<?php
/**
 * UserController class.
 * UserController is user action for API REST.
 * 
 * LBB Solutions Ltd. 版权所有 @ 2012.
 */
class UserController extends ApiController
{
	/**
	 * Login with Facebook/Twitter
	 */
	public function actionLogin()
	{
		$site_id = Yii::app()->request->getParam('site_id');
		if (empty($site_id)) $this->_sendError('Parameter site_id is missing!');
		$site_token = Yii::app()->request->getParam('site_token');
		if (empty($site_token)) $this->_sendError('Parameter site_token is missing!');
		$site_user_id = Yii::app()->request->getParam('site_user_id');
		if (empty($site_user_id)) $this->_sendError('Parameter site_user_id is missing!');
		
		$oUser = null;
		if ($site_id == 1) {//facebook login
			$facebook = $this->_getFacebookObject($site_token);
			$fbUser = $facebook->api('/' . $site_user_id . '?fields=id,email,username,name,picture,gender,location,locale');
			$oUser['id'] = $fbUser['id'];
			$oUser['email'] = $fbUser['email'];
			$oUser['username'] = $fbUser['username'];
			$oUser['name'] = $fbUser['name'];
			$oUser['picture'] = $fbUser['picture']['data']['url'];
			$oUser['gender'] = isset($fbUser['gender']) ? $fbUser['gender'] : '';
			$oUser['location'] = isset($fbUser['location']['name']) ? $fbUser['location']['name']: '';
			$oUser['lang'] = isset($fbUser['locale']) ? strtolower($fbUser['locale']): '';
			
			//Add a extend token of FB, Bocheng, 2012.12.31
			//refer: http://developers.facebook.com/docs/howtos/login/extending-tokens/
			$extend_token = $facebook->getExtendedAccessToken();
		} else {
			//TODO: twitter login
			$this->_sendError('Twitter login is not implemented!');
		}
		
		//1.search for user profile
		$sql_user = 'SELECT id, status, email, username, name, picture, gender, location, lang
			FROM tbl_user_account
			WHERE site_id=:site_id AND site_user_id=:site_user_id';
		$params = array(
			':site_id' => $site_id,
			':site_user_id' => $site_user_id,
		);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_user);
		$row = $command->queryRow(true, $params);
		
		if (empty($row)) {
			//create user account
			$params_more = $params;
			$params_more[':site_token'] = $extend_token;
			$params_more['email'] = $oUser['email'];
			$params_more['username'] = $oUser['username'];
			$params_more['picture'] = $oUser['picture'];
			$params_more['name'] = $oUser['name'];
			$params_more['gender'] = $oUser['gender'];
			$params_more['location'] = $oUser['location'];
			$params_more['lang'] = $oUser['lang'];
			$command = $connection->createCommand('INSERT INTO tbl_user_account (email, username, picture, site_id, site_user_id, site_token, name, gender, location, lang, last_login_time)
				VALUES(:email, :username, :picture, :site_id, :site_user_id, :site_token, :name, :gender, :location, :lang, NOW())');
			$command->execute($params_more);

			//get new user info
			$command = $connection->createCommand($sql_user);
			$row = $command->queryRow(true, $params);
		} else {
			//update info
			$param_upd = array(':id'=>$row['id'], ':site_token'=>$extend_token, ':email'=>$oUser['email']);
			$sql_upd = 'UPDATE tbl_user_account SET last_login_time=NOW(), site_token=:site_token, email=:email ';
			if (empty($row['picture']) and !empty($oUser['picture'])) {
				$param_upd['picture'] = $oUser['picture'];
				$sql_upd .= ', picture=:picture';
			}
			if (empty($row['gender']) and !empty($oUser['gender'])) {
				$param_upd['gender'] = $oUser['gender'];
				$sql_upd .= ', gender=:gender';
			}
			if (empty($row['location']) and !empty($oUser['location'])) {
				$param_upd['location'] = $oUser['location'];
				$sql_upd .= ', location=:location';
			}
			if (empty($row['lang']) and !empty($oUser['lang'])) {
				$param_upd['lang'] = $oUser['lang'];
				$sql_upd .= ', lang=:lang';
			}
			$sql_upd .= ' WHERE id=:id';
			$command = $connection->createCommand($sql_upd);
			$command->execute($param_upd);
			
			//get new user info
			$command = $connection->createCommand($sql_user);
			$row = $command->queryRow(true, $params);
		}
		$connection->active = false;
		
		//login
		if (!empty($row['id'])) {
			BUtils::Logging('login_fb', 'Facebook login done : ' . print_r($row, 1));

			//create a hash key: Hash32(id + timestamp)
			$created_time = time();
			$key32 = BUtils::Hash32($row['id'] . $created_time);	//TODO: save to key32 field in DB.
			$hashed_id = BUtils::Encrypt($row['id']);
			
			//send user info, hid, hkey
			$user = array(
				'email' => $row['email'],
				'name' => $row['name'],
				'picture' => $row['picture'],
				'location' => $row['location'],
				'lang' => $row['lang'],
				'extend_token' => empty($extend_token) ? '' : $extend_token,
			);
			$this->_sendJSON(200, array(
				'hid' => $hashed_id,
				'key' => $key32,
				'user'=>$user
			));
		} else {
			$this->_sendError('Login failed!');
		}
	}
	
	/**
	 * Validate hid and key to update user profile.
	 */
	public function actionAuth()
	{
		$hid = Yii::app()->request->getParam('hid', null);
		$key = Yii::app()->request->getParam('key', null);
		$id = $this->_auth($hid, $key);
		
		//1.search for user profile
		$sql_user = 'SELECT id, status, email, username, name, picture, gender, location, lang
			FROM tbl_user_account
			WHERE id=:id ';
		$params = array('id' => $id);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_user);
		$row = $command->queryRow(true, $params);
		if (empty($row)) {
			$this->_sendError('Your account is deleted!');
		}
		if ($row['status'] > 0) {
			$this->_sendError('Your account is locked!');
		}
		$user = array(
			'email' => $row['email'],
			'name' => $row['name'],
			'picture' => $row['picture'],
			'location' => $row['location'],
			'lang' => $row['lang'],
		);
		$this->_sendJSON(200, array('user'=>$user));
	}
}